import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/store'
import { useUserStore } from '@/store/user.ts'

const userStore = useUserStore(pinia)
NProgress.configure({ showSpinner: false })

// 定义白名单，在跳转这些路由时必须要登录
const writeList = ['/my', '/cart', '/order']
// @ts-ignore

// 全局导航守卫
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // 如果跳转的是白名单，进行判断
  if (writeList.includes(to.path)) {
    const token = userStore.token
    // 判断有没有token
    if (token) {
      try {
        //  获取用户信息，判断token是否过期
        await userStore.getUserInfo()
        next()
      }catch (error){
        // 获取用户信息失败，token失效，重新登陆
        next('/login')
      }
    } else {
      // 跳转白名单，且没有token
      next('/login')
    }
  } else {
    // 跳转非白名单，直接放行
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})
